package com.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;

import java.io.*;

/**
 * 该类用于文件传输
 */
public class FileClientService {

    /**
     *
     * @param src 源文件
     * @param dest 把文件传到该目录
     * @param sender 发送者id
     * @param receiver 接收者id
     */
    public void sendToOne(String src,String dest,String sender,String receiver){
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_FILE_MES);
        message.setSender(sender);
        message.setReceive(receiver);
        message.setSrc(src);
        message.setDest(dest);

        //读取文件,将文件内容读进字节数组中去
        FileInputStream fileInputStream=null;
        byte[] fileBytes=new byte[(int)new File(src).length()];
        try {
             fileInputStream = new FileInputStream(src);
             fileInputStream.read(fileBytes);
             //将读取文件内容的字节数组传给message
             message.setFileBytes(fileBytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭流
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            //提示
            System.out.println("\n"+sender+" 给 "+receiver+" 发送文件: "+src+"  到对方目录的  "+dest);
            //发送message
            try {
                ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(sender).getSocket().getOutputStream());
                oos.writeObject(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
